﻿using Freebase4net.Rest;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Freebase4net
{
    public abstract class BaseService<TResponse>
    {
        protected string _apiKey;
        protected abstract string _baseUrl { get; }

        public BaseService(string ApiKey)
        {
            _apiKey = ApiKey;
        }

        protected virtual TResponse ReadInternal(dynamic obj, params string[] additionalParams)
        {
            RestClient client = CreateRequest(obj);
            ProcessAdditionalParameters(client, additionalParams);
            var message = client.ExecuteResult();

            return CreateResponse(message);
        }

        protected virtual async Task<TResponse> ReadInternalAsync(dynamic obj, params string[] additionalParams)
        {
            RestClient client = CreateRequest(obj);
            ProcessAdditionalParameters(client, additionalParams);
            var restTask = await client.ExecuteResultAsync();
            TResponse responseTask = await Task.Factory.StartNew<TResponse>(() =>
                {
                    return CreateResponse(restTask);
                }
            );
            return responseTask;
        }

        private void ProcessAdditionalParameters(RestClient client, params string[] additionalParams)
        {
            foreach (var p in additionalParams)
            {
                var items = p.Split(new string[] { "," }, StringSplitOptions.None);
                string name = items[0];
                string value = items[1];
                client.AddParameter(name, value);
            }
        }

        protected abstract RestClient CreateRequest(dynamic query);        

        protected abstract TResponse CreateResponse(RestResponseMessage response);
    }
}
